package com.vcs.dao;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import com.googlecode.s2hibernate.struts2.plugin.annotations.SessionTarget;
import com.googlecode.s2hibernate.struts2.plugin.annotations.TransactionTarget;
import com.vcs.domain.Job;
import com.vcs.domain.QuickSearch;

public class SearchDAOImpl implements SearchDAO {

	Log log = LogFactory.getLog(SearchDAOImpl.class);

	@SessionTarget
	Session session;

	@TransactionTarget
	Transaction transaction;

	@Override
	public List<Job> quickSearchJobs(QuickSearch quickSearch) {
		log.info("quickSearchJobs()...");
		List<Job> jobList = new ArrayList<Job>();
		// step1: get search keywords and put them into any array.
		String searchKeywords = quickSearch.getKeywords();
		String[] aKeywords = searchKeywords.split(",");
		for (int i = 0; i < aKeywords.length; i++) {
			aKeywords[i] = aKeywords[i].trim();
			log.info("After trim" + aKeywords[i] + ".");
		}

		session.beginTransaction();
		// jobList = session.createCriteria(Job.class).list();
		Criteria crit = session
				.createCriteria(Job.class)
				.add(Restrictions.le("minExp",
						new Integer(quickSearch.getExperience())))
				.add(Restrictions.ge("maxExp",
						new Integer(quickSearch.getExperience())))
				.add(Restrictions.eq("jobLocation",
						new Integer(quickSearch.getLocation())));

		jobList = crit.list();
		// filter out jobs based on skills
		ArrayList<Job> lstFinal = new ArrayList<Job>();
		for (Job j : jobList) {
			String[] skills = j.getKeySkills().split(",");
			for (int i = 0; i < skills.length; i++) {
				skills[i] = skills[i].trim();
			}
			// now skills is ready to compare.
			for(int i = 0; i < aKeywords.length; i++){
				for(int k = 0; k<skills.length; k++){
					if(aKeywords[i].equalsIgnoreCase(skills[k])){
						if(lstFinal.contains(j)){
							// do nothing if job is alredy in list
						}else{
							// add job to list
							lstFinal.add(j);
						}
					}
				}
			}
			
		}

		//System.out.println(">>>>>>>>>>>>>>>>>>>>>" + jobList);
		log.info("1111111"+ jobList);
		log.info("2222222"+ lstFinal);
		//return jobList;
		return lstFinal;

	}
}
